//
// Created by hkkzzxz on 24-8-31.
//

#ifndef YUNSHI_HTTPCONNECTION_H
#define YUNSHI_HTTPCONNECTION_H

// http连接处理类

#include <memory>
#include <boost/asio.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>

#include "LogManager.h"

namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = beast::http;           // from <boost/beast/http.hpp>
namespace net = boost::asio;            // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>

class HttpConnection : public std::enable_shared_from_this<HttpConnection> {
public:
    explicit HttpConnection(tcp::socket socket) : tcpSocket(std::move(socket)) {}

    void start();

private:
    // 异步接收完整的http请求消息
    void readRequest();

    // 处理http请求
    void processRequest();

    // 回应http请求
    void writeResponse();

    // 超时检测
    void checkDeadline();

    // 存储客户端的TCP连接
    tcp::socket tcpSocket;
    //用于读取http请求时存储数据
    beast::flat_buffer httpBuffer{8192};
    //用于存储解析后的http请求
    http::request<http::dynamic_body> httpRequest;
    //用于存储将要发送的http响应
    http::response<http::dynamic_body> httpResponse;

    //处理超时
    net::steady_timer httpDeadline
            {
                    tcpSocket.get_executor(), std::chrono::seconds(15)
            };

    LogManager *logManager = LogManager::getInstance();
    std::shared_ptr<spdlog::logger> consoleLogger = logManager->getConsoleLogger();
    std::shared_ptr<spdlog::logger> fileLogger = logManager->getFileLogger();
};


#endif //YUNSHI_HTTPCONNECTION_H
